package com.atguigu.interview.study.thread;


import java.util.concurrent.TimeUnit;

class HoldLockThread implements Runnable {

    private String lockA;
    private String lockB;

    public HoldLockThread(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
        synchronized (lockA) {

            System.out.println(Thread.currentThread().getName() + "\t 自己持：" + lockA + "\t 尝试获得：" + lockB);
            // 睡两秒钟
            try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }

            synchronized (lockB) {
                System.out.println(Thread.currentThread().getName() + "\t 自己持：" + lockB + "\t 尝试获得：" + lockA);
            }
        }
    }
}
/**
 * @author gcq
 * @Create 2020-12-01
 * 死锁是指两个或两个以上的进程在执行的过程中，
 * 因争夺资源而造成的一种互相等待的现象，
 * 若无外力干涉那他们将无法推进下去，
 */
public class DeadLockDemo {
    public static void main(String[] args) {
        String lockA = "lockA";
        String lockB = "lockB";
        new Thread(new HoldLockThread(lockA,lockB),"ThreadAAA").start();
        new Thread(new HoldLockThread(lockB,lockA),"ThreadBBB").start();

        /**
         * Linux ps -ef | grep xxxx
         * windows下 java运行程序，也有类似ps的查看进程的命令，但是目前我们需要查看的只是java
         *          jps = java ps   jps -l
         *          jps -l 显示出它对应的java进程
             *          9072 com.atguigu.interview.study.thread.DeadLockDemo
             *          13848
             *          17480 org.jetbrains.jps.cmdline.Launcher
             *          17656 sun.tools.jps.Jps
         *          jstack 进入指定的java进程
         *
         *
         */
    }
}